package com.v1.video.activity;

import android.app.ActivityManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.iss.view.common.ToastAlone;
import com.starschina.sdk.player.ThinkoEnvironment;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.AppContext;
import com.v1.video.AppManager;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.R.color;
import com.v1.video.domain.ActionItem;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.LoginUserStateCheckEntity;
import com.v1.video.domain.MaiPaigeActivityInfo;
import com.v1.video.domain.MaiPaigeGame;
import com.v1.video.domain.MaiPaigeLiveInfo;
import com.v1.video.domain.MaiPaigeLoadinImage;
import com.v1.video.domain.MainPageUploadEntity;
import com.v1.video.domain.MainPageUploadEntity.BuddhistInfo;
import com.v1.video.domain.VersionCheckPageInfo2;
import com.v1.video.engine.RequestEngine;
import com.v1.video.fragment.MainPageBuddhismFragment;
import com.v1.video.fragment.MainPageHeadlineFragment;
import com.v1.video.fragment.MainPageMyFragement2;
import com.v1.video.fragment.MainPageThemeFragment;
import com.v1.video.fragment.SecondFragment;
import com.v1.video.fragment.V1BaseFragment;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.ImageGetFromHttp;
import com.v1.video.util.Logger;
import com.v1.video.util.PreferencesUtils;
import com.v1.video.util.SDCardFileUtils;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.util.WindowUtils;
import com.v1.video.view.CustomActionSheetDialog;
import com.v1.video.view.PopupMenuControl;
import com.v1.video.view.PopupMenuControl.OnItemOnClickListener;
import com.v1.video.view.PopupMenuControl.OnWindowCloseListener;
import com.v1.video.widgets.MyDialog;

import java.io.File;
import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.ShareSDK;

/**
 * @author wangfang
 */
public class MainPageNewActivity extends BaseActivity implements
        OnClickListener, OnLongClickListener, OnItemOnClickListener,
        OnWindowCloseListener {

    public final String TAG = "MainPageNewActivtiy";
    private static final int FINISH_APP = 1000;
    private static final int FINISH_LOAD_STAR_USERINFO = 1003;
    private static final long DELAYED_FINISH_TIME = 3000; // 点击两次back键的时间
    public static final int FLAG_HEADLINE = 0;
    public static final int FLAG_THEME = 1;
    public static final int FLAG_SECOND = 2;
    public static final int FLAG_PERSONAL = 3;
    public static final int FLAG_BUDDHISM = 4;

    private static final String RECORD_VIDEO = "10";// 拍摄视频
    private static final String CHECK_LOCAL = "11";// 选取本地
    private static final String LOOK_STATE = "12";// 查看已上传

    private int mCurIndex = -1;

    public int getmCurIndex () {
        return mCurIndex;
    }

    private MyDialog dialogCommon;
    private ImageView mIvhome, mIvFind, mIvSubscribe, mIvPersonal, mIvBuddhism;
    private TextView mTvhome, mTvFind, mTvSubscribe, mTvPersonal, mTvBuddhism;
    private boolean canFinish = false;

    private FragmentManager mFragmentManager = null;

    private Fragment mCurFragmet;// 当前选中的fragment
    private CustomActionSheetDialog mCasdialog;
    private boolean isLoginOut = false;// 是否注销
    private ImageView mUpload;
    private ImageView mSearch;
    // 定义弹出菜单
    private PopupMenuControl mUploadMenu;
//	private LinearLayout mLayBuddhism;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.i("anr", "create");
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);
        setContentView(R.layout.activity_mainpage_new);
        Utils.mainPageActivity = this;
        try {
            ThinkoEnvironment.setUp(getApplicationContext());
        } catch (IllegalArgumentException e) {
            // appkey is null
        }
    }

    @Override
    protected void onNewIntent (Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey("tag")) {
            if (mCurIndex != bundle.getInt("tag")) {
                isLoginOut = true;
                setCurPageSelected(bundle.getInt("tag"));
                isLoginOut = false;
            }
        }
    }

    @Override
    public void onPause () {
        super.onPause();
        MobclickAgent.onPageEnd("主页");
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume () {
        super.onResume();
        Logger.i(TAG, "MainPageNewActivity的onResume执行了");
        MobclickAgent.onPageStart("主页");
        MobclickAgent.onResume(this);

        if (LoginInfo.getInstance().isLogin()) {
            checkUserState();
        }
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        int heapSize = manager.getLargeMemoryClass();
        Logger.i(TAG, "manager.getLargeMemoryClass()==" + heapSize);

    }

    @Override
    protected void initView () {

        mUpload = (ImageView) findViewById(R.id.upload);
        mSearch = (ImageView) findViewById(R.id.search);

        mUploadMenu = new PopupMenuControl(this, WindowUtils.dip2px(this, 132),
                LayoutParams.WRAP_CONTENT);
        mUploadMenu.setItemOnClickListener(this);
        mUploadMenu.setWindowCloseListener(this);

        mFragmentManager = this.getSupportFragmentManager();
        mIvhome = (ImageView) findViewById(R.id.iv_home);
        mIvFind = (ImageView) findViewById(R.id.iv_find);
        mIvSubscribe = (ImageView) findViewById(R.id.iv_subscribe);
        mIvPersonal = (ImageView) findViewById(R.id.iv_personal);
        mTvhome = (TextView) findViewById(R.id.tv_home);
        mTvFind = (TextView) findViewById(R.id.tv_find);
        mTvSubscribe = (TextView) findViewById(R.id.tv_subscribe);
        mTvPersonal = (TextView) findViewById(R.id.tv_personal);
        tv_miantitle = (TextView) findViewById(R.id.tv_miantitle);
        titleLayout = findViewById(R.id.titleLayout);
        fl_title = findViewById(R.id.fl_title);
    }

    @Override
    protected void initData () {
        // TODO Auto-generated method stub
        String buddhistState = PreferencesUtils.getInstance(
                MainPageNewActivity.this).getString("buddhistState", "1");
        // 给标题栏弹窗添加子类
        mUploadMenu.addAction(ActionItem.builder(this).setId(RECORD_VIDEO)
                .setTitle("拍摄视频").setIcon(R.drawable.record_video));
        mUploadMenu.addAction(ActionItem.builder(this).setId(CHECK_LOCAL)
                .setTitle("选取本地").setIcon(R.drawable.check_local));
        mUploadMenu.addAction(ActionItem.builder(this).setId(LOOK_STATE)
                .setTitle("查看已上传").setIcon(R.drawable.look_state));

        LoginInfo.getInstance().getLoginInfo(this);
        if (LoginInfo.getInstance().isLogin()) {
            if (LoginInfo.getInstance().getToken() == null
                    || LoginInfo.getInstance().getToken().length() <= 0) {
                LoginInfo.getInstance().clear(getApplication());
            }
            new AsyncLoadStarUserInfo().execute();
        }
        getUpdataFrom();
        mIvhome.setImageResource(R.drawable.main_home_press);
        mTvhome.setTextColor(this.getResources().getColor(
                color.color_005fff));
        mCurIndex = FLAG_HEADLINE;
        changeFragment(FLAG_HEADLINE);
        setAliasAndTags();
    }

    @Override
    protected void setListener () {
        // TODO Auto-generated method stub
        findViewById(R.id.lay_home).setOnClickListener(this);
        findViewById(R.id.lay_subscribe).setOnClickListener(this);
        findViewById(R.id.lay_find).setOnClickListener(this);
        findViewById(R.id.lay_personal).setOnClickListener(this);

        findViewById(R.id.lay_home).setOnLongClickListener(this);
        findViewById(R.id.lay_subscribe).setOnLongClickListener(this);
        findViewById(R.id.lay_find).setOnLongClickListener(this);
        findViewById(R.id.lay_personal).setOnLongClickListener(this);

        mUpload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick (View v) {
                clickStatistics(Constant.UPDATE_ID, "首页上传");
                // createVideoActionSheet();
                mUploadMenu.show(v);
            }
        });
        mSearch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick (View v) {
                Intent intent_search = new Intent(MainPageNewActivity.this,
                        OptionSearchActivity.class);
                MainPageNewActivity.this.startActivity(intent_search);
                // MobclickAgent.onEvent(this, "search_id");
            }
        });
    }

    @Override
    public void onItemClick (ActionItem item, int position) {
        mUploadMenu.dismiss();
        switch (position) {
            case 0:
                File destDir = new File(Environment.getExternalStorageDirectory(),
                        "/DCIM/Camera");
                if (!destDir.exists()) {
                    destDir.mkdirs();
                }
                Uri uri = Uri.fromFile(new File(destDir, "VID_"
                        + System.currentTimeMillis() + ".mp4"));
                ContentValues cv = new ContentValues();
                cv.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
                cv.put(MediaStore.Video.Media.DATA, uri.getPath());
                Uri mUri = MainPageNewActivity.this.getContentResolver().insert(
                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cv);
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                startActivityForResult(intent, Constant.REQUEST_CODE_VIDEO_CAPTURE);
                break;
            case 1:
                Intent intent2 = new Intent();
                intent2.setClass(MainPageNewActivity.this,
                        MediaStoreVideoList.class);
                startActivityForResult(intent2, Constant.REQUEST_CODE_VIDEO_SELECT);
                break;
            case 2:
                if (LoginInfo.getInstance().isLogin()) {
                    Intent center = new Intent(this, UploadingVideoActivity.class);
                    center.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    center.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(center);
                } else {
                    Intent intent_login = new Intent(this,
                            SettingLoginActivity.class);
                    intent_login.putExtra("loginFlag", 130);
                    startActivityForResult(intent_login,
                            Constant.REQUESTCODE_LOGIN_CODE);
                }
                break;
        }

    }

    @Override
    public void onDimiss (PopupMenuControl pc) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FLAG_THEME:
                if (resultCode == RESULT_OK) {
                    if (mCurIndex != FLAG_THEME) {
                        setCurPageSelected(FLAG_THEME);
                    } else {
                        Fragment f = mFragmentManager
                                .findFragmentByTag("ThemeFragment");
                        if (f != null) {
                            ((V1BaseFragment) f).refresh(null);
                        }
                    }
                }
                break;
            case FLAG_PERSONAL:
                if (resultCode == RESULT_OK) {
                    if (mCurIndex != FLAG_PERSONAL) {
                        setCurPageSelected(FLAG_PERSONAL);
                    } else {
                        Fragment f = mFragmentManager
                                .findFragmentByTag("MyFragement");
                        if (f != null) {
                            ((V1BaseFragment) f).refresh(null);
                        }
                    }
                }
                break;
            case Constant.REQUEST_CODE_VIDEO_CAPTURE:
                if (resultCode == RESULT_OK && data != null) {
                    Uri mUri = data.getData();
                    if (mUri != null) {
                        Intent intent = new Intent(this, SaveShareActivity.class);
                        intent.putExtra("videoUri", mUri);
                        intent.putExtra("sourceType", "video");
                        startActivity(intent);
                    }
                }
                break;
            case Constant.REQUEST_CODE_VIDEO_SELECT:
                if (resultCode == RESULT_OK && data != null) {
                    Uri mUri = data.getData();
                    if (mUri != null) {
                        Intent intent = new Intent(this, SaveShareActivity.class);
                        intent.putExtra("videoUri", mUri);
                        intent.putExtra("sourceType", "video");
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    @Override
    public void onClick (View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.lay_home:
                if (mCurIndex != FLAG_HEADLINE) {
                    setCurPageSelected(FLAG_HEADLINE);
                }
                break;
            case R.id.lay_subscribe:
                clickStatistics(Constant.THEME_ID, "首页的主题");
                if (mCurIndex != FLAG_THEME) {
                    setCurPageSelected(FLAG_THEME);
                }
                break;

            case R.id.lay_find:
                if (mCurIndex != FLAG_SECOND) {
                    setCurPageSelected(FLAG_SECOND);
                }
                break;
            case R.id.lay_personal:
                if (mCurIndex != FLAG_PERSONAL) {
                    setCurPageSelected(FLAG_PERSONAL);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onLongClick (View v) {
        switch (v.getId()) {
            case R.id.lay_home:
                if (mCurIndex != FLAG_HEADLINE) {
                    setCurPageSelected(FLAG_HEADLINE);
                }
                break;
            case R.id.lay_subscribe:
                if (mCurIndex != FLAG_THEME) {
                    setCurPageSelected(FLAG_THEME);
                }
                break;
            case R.id.lay_find:
                if (mCurIndex != FLAG_SECOND) {
                    setCurPageSelected(FLAG_SECOND);
                }
                break;
            case R.id.lay_personal:
                if (mCurIndex != FLAG_PERSONAL) {
                    setCurPageSelected(FLAG_PERSONAL);
                }
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 设置当前页选择中状态
     *
     * @param index
     */
    private void setCurPageSelected (int index) {
        if (index == mCurIndex) {
            return;
        }
        switch (index) {
            case FLAG_HEADLINE:
                mIvhome.setImageResource(R.drawable.main_home_press);
                mTvhome.setTextColor(this.getResources().getColor(
                        color.color_005fff));
                mSearch.setVisibility(View.VISIBLE);
                mUpload.setVisibility(View.VISIBLE);
                fl_title.setVisibility(View.VISIBLE);
                titleLayout.setVisibility(View.VISIBLE);
                tv_miantitle.setVisibility(View.GONE);
                setOldPageSelected();
                break;
            case FLAG_THEME:
                mIvSubscribe.setImageResource(R.drawable.main_subscription_press);
                mTvSubscribe.setTextColor(this.getResources().getColor(
                        color.color_005fff));
                mSearch.setVisibility(View.GONE);
                mUpload.setVisibility(View.GONE);
                titleLayout.setVisibility(View.GONE);
                fl_title.setVisibility(View.VISIBLE);
                tv_miantitle.setVisibility(View.VISIBLE);
                tv_miantitle.setText("订阅");
                setOldPageSelected();
                break;
            case FLAG_SECOND:
                mIvFind.setImageResource(R.drawable.main_second_press);
                mTvFind.setTextColor(this.getResources().getColor(
                        color.color_005fff));
                mSearch.setVisibility(View.GONE);
                mUpload.setVisibility(View.GONE);
                fl_title.setVisibility(View.VISIBLE);
                titleLayout.setVisibility(View.GONE);
                tv_miantitle.setVisibility(View.VISIBLE);
                tv_miantitle.setText("秒评");
                setOldPageSelected();
                break;
            case FLAG_PERSONAL:
                mIvPersonal.setImageResource(R.drawable.main_me_press);
                mTvPersonal.setTextColor(this.getResources().getColor(
                        color.color_005fff));
                mSearch.setVisibility(View.GONE);
                mUpload.setVisibility(View.GONE);
                fl_title.setVisibility(View.GONE);
                setOldPageSelected();
                break;
            default:
                break;
        }
        changeFragment(index);
        mCurIndex = index;
    }

    /**
     * 设置旧页为不选择状态
     */
    private void setOldPageSelected () {
        switch (mCurIndex) {
            case FLAG_HEADLINE:
                mIvhome.setImageResource(R.drawable.main_home_normal);
                mTvhome.setTextColor(this.getResources().getColor(
                        color.color_333333));
                break;
            case FLAG_THEME:
                mIvSubscribe.setImageResource(R.drawable.main_subscription_normal);
                mTvSubscribe.setTextColor(this.getResources().getColor(
                        color.color_333333));
                break;
            case FLAG_SECOND:
                mIvFind.setImageResource(R.drawable.main_second_normal);
                mTvFind.setTextColor(this.getResources().getColor(
                        color.color_333333));
                break;
            case FLAG_PERSONAL:
                mIvPersonal.setImageResource(R.drawable.main_me_normal);
                mTvPersonal.setTextColor(this.getResources().getColor(
                        color.color_333333));
                break;
            default:
                break;
        }
    }

    /**
     * @param index
     */
    private void changeFragment (int index) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        switch (index) {
            case FLAG_HEADLINE:
                Fragment f = mFragmentManager.findFragmentByTag("SecondFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("ThemeFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("MyFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("BuddhismFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("HeadlineFragment");
                if (f != null) {
                    transaction.show(f);
                } else {
                    f = new MainPageHeadlineFragment();
                    transaction.add(R.id.lay_maincontent, f, "HeadlineFragment");
                }
                mCurFragmet = f;
                clickStatistics(Constant.HOME_ID);
                break;
            case FLAG_THEME:
                f = mFragmentManager.findFragmentByTag("MyFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("HeadlineFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("SecondFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("BuddhismFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("ThemeFragment");
                if (f != null) {
                    transaction.show(f);
                    ((V1BaseFragment) f).refresh(null);
                } else {
                    f = new MainPageThemeFragment();
                    transaction.add(R.id.lay_maincontent, f, "ThemeFragment");
                }
                clickStatistics(Constant.SUBSCRIBE_ID);
                break;
            case FLAG_SECOND:
                f = mFragmentManager.findFragmentByTag("ThemeFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("MyFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("HeadlineFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("BuddhismFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("SecondFragment");
                if (f != null) {
                    transaction.show(f);
                } else {
                    f = new SecondFragment();
                    transaction.add(R.id.lay_maincontent, f, "SecondFragment");
                }
                mCurFragmet = f;
                clickStatistics(Constant.H5GAME_ID);
                break;
            case FLAG_PERSONAL:
                f = mFragmentManager.findFragmentByTag("ThemeFragment");
                if (f != null) {
                    transaction.hide(f);
                }

                f = mFragmentManager.findFragmentByTag("HeadlineFragment");
                if (f != null) {
                    transaction.hide(f);
                }

                f = mFragmentManager.findFragmentByTag("SecondFragment");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("BuddhismFragement");
                if (f != null) {
                    transaction.hide(f);
                }
                f = mFragmentManager.findFragmentByTag("MyFragement");
                if (f != null) {
                    transaction.show(f);

                } else {
                    f = new MainPageMyFragement2();
                    transaction.add(R.id.lay_maincontent, f, "MyFragement");
                }
                mCurFragmet = f;
                clickStatistics(Constant.MY_ID);
                break;
            case FLAG_BUDDHISM:
                f = mFragmentManager.findFragmentByTag("ThemeFragment");
                if (f != null) {
                    transaction.hide(f);
                }

                f = mFragmentManager.findFragmentByTag("HeadlineFragment");
                if (f != null) {
                    transaction.hide(f);
                }

                f = mFragmentManager.findFragmentByTag("SecondFragment");
                if (f != null) {
                    transaction.hide(f);
                }

                f = mFragmentManager.findFragmentByTag("MyFragement");
                if (f != null) {
                    transaction.hide(f);
                }

                f = mFragmentManager.findFragmentByTag("BuddhismFragement");
                if (f != null) {
                    transaction.show(f);
                } else {
                    f = new MainPageBuddhismFragment();
                    transaction.add(R.id.lay_maincontent, f, "BuddhismFragement");
                }
                mCurFragmet = f;
                clickStatistics(Constant.MY_ID);
                break;
            default:
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown (int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Logger.i(TAG, "MainPageNewActivity的onKeyDown方法执行了。。。");
            if (canFinish) {
                AppManager.getAppManager().AppExit(this);
                // finish();
            } else {
                ToastAlone.showToast(this, R.string.finish_app, 1);
                canFinish = true;
                handler.sendEmptyMessageDelayed(FINISH_APP,
                        DELAYED_FINISH_TIME);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage (Message msg) {
            switch (msg.what) {
                case FINISH_APP:// 退出应用
                    canFinish = false;
                    break;
                case FINISH_LOAD_STAR_USERINFO:
//				String str = "\"localCateGroup\"\\s*:\\s*{\\s*.*\\s*.*\\s*},\\s*";
                    getTheStarUserInfoToServer((String) msg.obj);
                    break;
            }
        }
    };
    private TextView tv_miantitle;
    private View titleLayout;
    private View fl_title;

    private void getTheStarUserInfoToServer (String str) {
        String url = V1VideoHttpApi.GET_STAR_USER_INFO_TO_SERVER() + "&devid=" + Constant.DEVICEID + "&uid=" + LoginInfo.getInstance().getUserId() +
                "&keystr=" + str;

        RequestManager.getInstance().getRequest(MainPageNewActivity.this, url,
                null, MainPageUploadEntity.class, 0, "MainPageNewActivity",
                new OnResponseListener() {

                    @Override
                    public void onSuccess (Object object, int code,
                                           String message, String key) {
                        // TODO Auto-generated method stub
                        Logger.i(TAG, "onSuccess.object=" + object.toString());

                        if (object != null) {
                        }
                    }

                    @Override
                    public void onFailure (int code, String message) {
                        // TODO Auto-generated method stub
                        Logger.i("tag---onFailure", message);
                    }

                });
    }

    /***
     * 更新版本的提示 4.0
     *
     * @param msg
     * @param url
     * @param forceUp
     */
    private void updataShow (String msg, final String url, final String forceUp) {
        if (dialogCommon != null) {
            dialogCommon = null;
        }
        dialogCommon = new MyDialog(this, R.style.dialog_custom, true);
        RelativeLayout linearlayout;
        android.view.WindowManager.LayoutParams layoutparams;
        linearlayout = (RelativeLayout) ((LayoutInflater) this
                .getSystemService("layout_inflater")).inflate(
                R.layout.dialog_version_updata, null);
        linearlayout.setMinimumWidth(10000);

        dialogCommon.setCanceledOnTouchOutside(true);
        dialogCommon.setContentView(linearlayout);
        dialogCommon.setCancelable(false);
        dialogCommon.setCanceledOnTouchOutside(false);

        if (!msg.equals("")) {
            String strMess = msg.trim();
            ((TextView) dialogCommon.findViewById(R.id.version_intro_1))
                    .setText(strMess);
        } else {
            ((TextView) dialogCommon.findViewById(R.id.version_intro_1))
                    .setText(getResources()
                            .getString(R.string.version_updata_1)
                            + "Ver"
                            + Constant.PRODUCT_VERSION);
        }
        dialogCommon.findViewById(R.id.version_btn_cancel).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick (View arg0) {
                        // TODO Auto-generated method stub
                        dialogCommon.dismiss();
                        if (forceUp.equals("1")) {
                            // 强制退出
                            AppManager.getAppManager().AppExit(
                                    MainPageNewActivity.this);
                        }
                    }
                });
        dialogCommon.findViewById(R.id.version_btn_sure).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick (View arg0) {
                        // TODO Auto-generated method stub
                        dialogCommon.dismiss();
                        if (url != null && url.length() >= 5) {
                            Uri uri = Uri.parse(url);
                            Intent it = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(it);
                        }
                    }
                });
        dialogCommon.show();
    }

    private void getUpdataFrom () {
        String url = String.format(V1VideoHttpApi.GET_UPLOAD_DATA(), Constant.DEVICEID,
                android.os.Build.VERSION.RELEASE);
        ParamList params = new ParamList();
        params.add(new Parameter("androidid", Constant.DEVICEID));
        params.add(new Parameter("idfa", ""));
        params.add(new Parameter("mac", Utils.getMacAddress(this)));
        params.add(new Parameter("aaid", ""));
        params.add(new Parameter("appPn", "com.v1.video"));
        params.add(new Parameter("imgWidth", Utils.getScreenWidth(this) + ""));
        params.add(new Parameter("imgHeight", Utils.getScreenHeight(this) + ""));
        Logger.i(TAG, "开机接口： url=" + url);
        RequestManager.getInstance().getRequest(MainPageNewActivity.this, url,
                null, MainPageUploadEntity.class, 0, "MainPageNewActivity",
                new OnResponseListener() {

                    @Override
                    public void onSuccess (Object object, int code,
                                           String message, String key) {
                        // TODO Auto-generated method stub
                        Logger.i(TAG, "onSuccess.object=" + object.toString());

                        if (object != null) {
                            MainPageUploadEntity mainData = (MainPageUploadEntity) object;
                            if (mainData.getHeader() != null) {
                                if (mainData.getHeader().getStatus()
                                        .equals("1")) {
                                    VersionCheckPageInfo2 version = mainData
                                            .getBody().getUpgrade();
                                    if (version != null) {
                                        if (!version.getUptype().equals("0")) {// 0不升级，1强制升级
                                            // 2不强制升级
                                            updataShow(version.getMsg(),
                                                    version.getUrl(),
                                                    version.getUptype());
                                        }
                                    }
                                    MaiPaigeLiveInfo liveInfo = mainData
                                            .getBody().getIslive();
                                    AppContext context = (AppContext) getApplicationContext();
                                    context.setLiveInfo(liveInfo);
                                    MaiPaigeLoadinImage loadingInfo = mainData
                                            .getBody().getBootimg();
                                    if (loadingInfo != null) {
                                        if (!Constant.isDownLoadedImg) {
                                            if (loadingInfo.getImgUrl() != null
                                                    && loadingInfo.getImgUrl()
                                                    .length() >= 5) {
                                                new AsyncLoadImage(loadingInfo
                                                        .getImgUrl())
                                                        .execute();
                                            }
                                        }
                                        Gson gson = new Gson();
                                        String jsonStr = gson.toJson(loadingInfo);
                                        Utility.CacheData(MainPageNewActivity.this, "AdvCache.txt",
                                                jsonStr);
                                    }
//									MaiPaigeAD ad = mainData.getBody().getAd();
//									if (ad.getUrl() != null) {
//										// 存到preference里
//										editSaveGuangGao(ad.getUrl());
//									} else {
//										editSaveGuangGao("");
//									}

                                    MaiPaigeGame game = mainData.getBody()
                                            .getGame();
                                    if (game.getUrl() != null
                                            && game.getUrl().length() >= 5) {
                                        // 存到application里
                                        Logger.i(
                                                TAG,
                                                "game.getUrl()=="
                                                        + game.getUrl());
                                        AppContext application = (AppContext) getApplication();
                                        application.setUrlH5Game(game.getUrl());
                                    }
                                    MaiPaigeActivityInfo activity = mainData
                                            .getBody().getActivity();
                                    if (activity.getUrl() != null
                                            && activity.getUrl().length() >= 5) {
                                        // 存到application里
                                        Logger.i(TAG, "activity.getUrl()=="
                                                + activity.getUrl());
                                        editSave1yuanDuoBao(activity.getUrl());
                                        AppContext application = (AppContext) getApplication();
                                        application.setActivityInfo(activity
                                                .getUrl());
                                    }
                                    BuddhistInfo buddhistInfo = mainData.getBody().getBuddhist();
                                    if (buddhistInfo != null
                                            && !TextUtils.isEmpty(buddhistInfo
                                            .getStatus())) {
                                        PreferencesUtils.getInstance(
                                                MainPageNewActivity.this)
                                                .putString(
                                                        "buddhistState",
                                                        buddhistInfo
                                                                .getStatus());
                                    }
                                    AppContext.getInstance().buddhism_titles = mainData
                                            .getBody().getTag_titles();
                                } else {
                                    // ToastAlone.showToast(MainPageNewActivity.this,
                                    // mainData.getHeader().getMessage(), 1);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure (int code, String message) {
                        // TODO Auto-generated method stub
                        Logger.i("tag---onFailure", message);
                    }

                });
    }

    private class AsyncLoadStarUserInfo extends AsyncTask<Void, Void, Void> {

        String userInfo = "";

        @Override
        protected Void doInBackground (Void... params) {
            // TODO Auto-generated method stub
            RequestEngine request = new RequestEngine();
            userInfo = request.getV1StarUserInfo();
            return null;
        }

        @Override
        protected void onPostExecute (Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (userInfo != null && userInfo.length() >= 1) {
                if (handler != null) {
                    Message msg = handler.obtainMessage();
                    msg.what = FINISH_LOAD_STAR_USERINFO;
                    msg.obj = userInfo;
                    handler.sendMessage(msg);
                }
            }
        }

    }

    private class AsyncLoadImage extends AsyncTask<Void, Void, Void> {
        String downUrl = "";

        public AsyncLoadImage (String downUrl) {
            this.downUrl = downUrl;
        }

        @Override
        protected Void doInBackground (Void... params) {
            // TODO Auto-generated method stub
            try {
                ImageGetFromHttp.download(MainPageNewActivity.this, downUrl,
                        "load.jpg");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute (Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Constant.isDownLoadedImg = true;
            editSaveLoadImg();
        }

    }

    private void editSaveLoadImg () {
        SharedPreferences sp = getSharedPreferences(Constant.APP_INFO,
                MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.putString("loading_page_path", SDCardFileUtils.getSDCardPath()
                + "V1/cache/load.jpg");
        edit.commit();
    }

    private void editSaveGuangGao (String url) {
        SharedPreferences sp = getSharedPreferences(Constant.APP_INFO,
                MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.putString("advUrl", url);
        edit.commit();
    }

    private void editSave1yuanDuoBao (String url) {
        SharedPreferences sp = getSharedPreferences(Constant.APP_INFO,
                MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.putString("activity1yuan", url);
        edit.commit();
    }

    @Override
    protected void onDestroy () {
        // TODO Auto-generated method stub
        if (mCasdialog != null) {
            if (mCasdialog.isShowing()) {
                mCasdialog.dismiss();
            }
            mCasdialog = null;
        }
        ThinkoEnvironment.tearDown();
        super.onDestroy();
    }

    private void checkUserState () {
        String url = V1VideoHttpApi.GET_CHECK_USER_STATE() + "&token="
                + LoginInfo.getInstance().getToken() + "&devid="
                + Constant.DEVICEID;
        Logger.i(TAG, "检查用户状态URL=" + url);
        RequestManager.getInstance().getRequest(MainPageNewActivity.this, url,
                null, LoginUserStateCheckEntity.class, 0,
                "MainPageNewActivity", new OnResponseListener() {

                    @Override
                    public void onSuccess (Object object, int code,
                                           String message, String key) {
                        // TODO Auto-generated method stub
                        Logger.i(TAG, "onSuccess.object=" + object.toString());
                        if (object != null) {
                            LoginUserStateCheckEntity entity = (LoginUserStateCheckEntity) object;
                            com.v1.video.domain.BaseEntity.Header header = entity
                                    .getHeader();
                            if (header == null) {
                                // toast("未知错误~");
                                return;
                            } else if (!header.getStatus().equals("1")) {
                                // toast(header.getMessage());
                                return;
                            } else if (header.getStatus().equals("1")) {
                                if (entity.getBody() != null) {
                                    if (entity.getBody().getStatus()
                                            .equals("1")) {

                                    } else {
                                        LoginInfo.getInstance().clear(
                                                MainPageNewActivity.this);
                                    }
                                } else {
                                    // toast(header.getMessage());
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure (int code, String message) {
                        // TODO Auto-generated method stub
                        Logger.i("tag---onFailure", message);
                    }

                });
    }

    private void setAliasAndTags () {
        Set<String> tagSet = new LinkedHashSet<String>();
        tagSet.add(Constant.DEVICEID);
        JPushInterface.setAliasAndTags(getApplicationContext(),
                Constant.DEVICEID, tagSet, new TagAliasCallback() {

                    @Override
                    public void gotResult (int arg0, String arg1,
                                           Set<String> arg2) {
                        // TODO Auto-generated method stub
                        switch (arg0) {
                            case 0:
                                Logger.i(TAG, "Set tag and alias success");
                                break;
                            case 6002:
                                Logger.i(TAG, "Failed to set alias and tags due to timeout. Try again after 60s.");
                                break;
                            default:
                                Logger.e(TAG, "Failed with errorCode = " + arg0);
                        }
                    }

                });
    }
}
